#include "stdafx.h"	
#include "../sgp/RandomManager.h"

namespace ja2{ namespace sgp
{
	std::uint32_t RandomManager::get_random_number(std::uint32_t MaxNumber) const
	{
		return do_get_random_number(MaxNumber);
	}

	bool RandomManager::chance(std::uint_least32_t MaxNumber) const
	{
		return (get_random_number(100) < MaxNumber);
	}

	std::uint32_t RandomManager::get_real_random(std::uint32_t MaxNumber) const
	{
		static std::uint_least32_t rnd = 0, cnt = 0;
		if(MaxNumber == 0)
			return 0;
		if(!(cnt++ % RANDOM_MAX))
			srand(static_cast<unsigned int>(MaxNumber ^ rnd ^ time(0) ^ GetTickCount()));

		rnd = rand();
		rnd <<= 11;
		rnd ^= rand();
		rnd <<= 7;
		rnd ^= rand();

		return(rnd % MaxNumber);
	}

	std::uint32_t RandomManager::do_get_random_number(std::uint32_t MaxNumber) const
	{
		return get_real_random(MaxNumber);
	}

	//-------------------------------//

	MultiplayerRandomManager::MultiplayerRandomManager()
		: m_Index(0)
	{
		// Pre-generate all of the random numbers.
		for(auto it = m_PreRandomNumbers.begin(), end = m_PreRandomNumbers.end(); it != end; ++it)
			*it = get_real_random(std::numeric_limits<std::uint32_t>::max());
	}

	std::uint32_t MultiplayerRandomManager::do_get_random_number(std::uint32_t MaxNumber) const
	{
		if(MaxNumber == 0 )
			return 0;
		// Extract the current pregenerated number
		std::uint32_t const number = (m_PreRandomNumbers.at(m_Index++ % MAX_PREGENERATED_NUMS) * MaxNumber / RAND_MAX) % MaxNumber;

//		if (gfMPDebugOutputRandoms)
//		{
//			char tmpMPDbgString[512];
//			sprintf(tmpMPDbgString,"MPPreRandom ( uiRange : %i , uiPreRandomIndex : %i , uiResult : %i  )\n",uiRange, guiPreRandomIndex , number );
//			MPDebugMsg(tmpMPDbgString);
//		}
		
		return number;
	}
} /*sgp*/} /*ja2*/